package org.csu.mypetstore.web.servlets;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.LogService;
import org.csu.mypetstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class ListOrdersServlet extends HttpServlet {

    private static final String LIST_ORDERS = "/WEB-INF/jsp/order/ListOrders.jsp";

    private List<Order> orderList;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

//        AccountActionBean accountBean = (AccountActionBean) session.getAttribute("/actions/Account.action");
        OrderService orderService = new OrderService();
        Account account = (Account) session.getAttribute("account");
        orderList = orderService.getOrdersByUsername(account.getUsername());
        session.setAttribute("orderList", orderList);

//        return new ForwardResolution(LIST_ORDERS);
        JSONObject res = new JSONObject();
        JSONArray ol = JSONArray.parseArray(JSON.toJSONString(orderList));
        res.put("order_list", ol);

        String res_str = JSON.toJSONString(res);
        response.setContentType("text/json");
        PrintWriter out = response.getWriter();

        if(account != null){
            HttpServletRequest httpRequest= request;
            String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?";

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + strBackUrl + LIST_ORDERS;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }

        out.print(res_str);

        out.flush();
        out.close();

//        request.getRequestDispatcher(LIST_ORDERS).forward(request, response);
    }
}
